package com.tedu.bank_ems1.controller;

import com.tedu.bank_ems1.entity.Emp;
import com.tedu.bank_ems1.service.impl.EmpServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

/**
 * Author：毕龙
 * Date: 2024/6/26 9:12
 */
@WebServlet("/add/emp")
public class AddEmpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //请求参数乱码解决
            req.setCharacterEncoding("utf-8");

            //获取参数
            String name = req.getParameter("name");
            String salary = req.getParameter("salary");
            String age = req.getParameter("age");
            String birthday = req.getParameter("birthday");
            String deptId = req.getParameter("deptId");

            System.out.println(name);
            System.out.println(salary);
            System.out.println(age);
            System.out.println(birthday);
            System.out.println(deptId);

            //对数据进行转型
            double salaryData = Double.valueOf(salary);
            Integer ageData = Integer.valueOf(age);
            //将字符串的类型转化为Date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthdayData = sdf.parse(birthday);


            Integer deptIdData = Integer.valueOf(deptId);

            //对数据进行封装
            Emp emp = new Emp();
            emp.setName(name)
                    .setSalary(salaryData)
                    .setAge(ageData)
                    .setBirthday(birthdayData)
                    .setDeptId(deptIdData);

            //调用业务逻辑
            EmpServiceImpl service = new EmpServiceImpl();
            service.insertEmp(emp);


            //页面跳转
            resp.sendRedirect(req.getContextPath()+"/emp/list");
        } catch (Exception e) {
            System.out.println(e);
            resp.sendRedirect(req.getContextPath()+"/ems/emp/addEmp.jsp");
        }


    }
}
